package com.ruoyi.monitor.service.impl;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

import com.ruoyi.base.domain.BusWaterSegment;
import com.ruoyi.base.domain.BussinessItemVo;
import com.ruoyi.base.mapper.BusWaterSegmentMapper;
import com.ruoyi.base.service.PublicToolsService;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.js.ItemCodeOverData;
import com.ruoyi.common.utils.js.Standard;
import com.ruoyi.common.utils.js.WaterLevelCompute;
import com.ruoyi.monitor.domain.BusWaterAutomonitorHourdata;
import com.ruoyi.monitor.domain.BusWaterAutomonitorevaluateDaydata;
import com.ruoyi.monitor.domain.GetWaterAutomonitorParam;
import com.ruoyi.monitor.mapper.BusWaterAutomonitorevaluateDaydataMapper;
import com.ruoyi.utli.SegmentFormula;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.monitor.mapper.BusWaterAutomonitorDaydataMapper;
import com.ruoyi.monitor.domain.BusWaterAutomonitorDaydata;
import com.ruoyi.monitor.service.IBusWaterAutomonitorDaydataService;
import org.springframework.util.CollectionUtils;

/**
 * 水监测日数据Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-08-16
 */
@Service
public class BusWaterAutomonitorDaydataServiceImpl implements IBusWaterAutomonitorDaydataService 
{
    @Autowired
    private BusWaterAutomonitorDaydataMapper busWaterAutomonitorDaydataMapper;
    @Autowired
    private PublicToolsService publicToolsService;
    @Autowired
    private BusWaterSegmentMapper busWaterSegmentMapper;
    @Autowired
    private SegmentFormula segmentFormula;
    @Autowired
    private BusWaterAutomonitorevaluateDaydataMapper busWaterAutomonitorevaluateDaydataMapper;

    /**
     * 查询水监测日数据
     * 
     * @param mn 水监测日数据主键
     * @return 水监测日数据
     */
    @Override
    public BusWaterAutomonitorDaydata selectBusWaterAutomonitorDaydataByMn(String mn)
    {
        return busWaterAutomonitorDaydataMapper.selectBusWaterAutomonitorDaydataByMn(mn);
    }

    /**
     * 查询水监测日数据列表
     * 
     * @param busWaterAutomonitorDaydata 水监测日数据
     * @return 水监测日数据
     */
    @Override
    public List<BusWaterAutomonitorDaydata> selectBusWaterAutomonitorDaydataList(BusWaterAutomonitorDaydata busWaterAutomonitorDaydata)
    {
        return busWaterAutomonitorDaydataMapper.selectBusWaterAutomonitorDaydataList(busWaterAutomonitorDaydata);
    }

    /**
     * 新增水监测日数据
     * 
     * @param busWaterAutomonitorDaydata 水监测日数据
     * @return 结果
     */
    @Override
    public int insertBusWaterAutomonitorDaydata(BusWaterAutomonitorDaydata busWaterAutomonitorDaydata)
    {
        return busWaterAutomonitorDaydataMapper.insertBusWaterAutomonitorDaydata(busWaterAutomonitorDaydata);
    }

    /**
     * 修改水监测日数据
     * 
     * @param busWaterAutomonitorDaydata 水监测日数据
     * @return 结果
     */
    @Override
    public int updateBusWaterAutomonitorDaydata(BusWaterAutomonitorDaydata busWaterAutomonitorDaydata)
    {
        return busWaterAutomonitorDaydataMapper.updateBusWaterAutomonitorDaydata(busWaterAutomonitorDaydata);
    }

    /**
     * 批量删除水监测日数据
     * 
     * @param mns 需要删除的水监测日数据主键
     * @return 结果
     */
    @Override
    public int deleteBusWaterAutomonitorDaydataByMns(String[] mns)
    {
        return busWaterAutomonitorDaydataMapper.deleteBusWaterAutomonitorDaydataByMns(mns);
    }

    /**
     * 删除水监测日数据信息
     * 
     * @param mn 水监测日数据主键
     * @return 结果
     */
    @Override
    public int deleteBusWaterAutomonitorDaydataByMn(String mn)
    {
        return busWaterAutomonitorDaydataMapper.deleteBusWaterAutomonitorDaydataByMn(mn);
    }

    @Override
    public List<BusWaterAutomonitorDaydata> selectBusWaterAutomonitorDaydataItemList(GetWaterAutomonitorParam getWaterAutomonitorParam) {
        if (StringUtils.isNotEmpty(getWaterAutomonitorParam.getSegmentid()) && getWaterAutomonitorParam.getSegmentid().contains(",")) {
            getWaterAutomonitorParam.setSegmentidList(Arrays.asList(getWaterAutomonitorParam.getSegmentid().split(",")));
            getWaterAutomonitorParam.setSegmentid(null);
        }
        if(StringUtils.isNotEmpty(getWaterAutomonitorParam.getItemcode()) && getWaterAutomonitorParam.getItemcode().contains(",")){
            getWaterAutomonitorParam.setItemCodeList(Arrays.asList(getWaterAutomonitorParam.getItemcode().split(",")));
            getWaterAutomonitorParam.setItemcode(null);
        }
        List<BusWaterAutomonitorDaydata> list = busWaterAutomonitorDaydataMapper.selectBusWaterAutomonitorDaydataItemList(getWaterAutomonitorParam);
        list.forEach(item->{
            BigDecimal effectivevalue = item.getEffectivevalue();
            DecimalFormat df = new DecimalFormat("###.#####");
            String evalue = df.format(effectivevalue);
            item.setEffectivevalue(BigDecimal.valueOf(Double.valueOf(evalue)));
        });
        return list;
    }

    @Override
    public Map statisCalendarDetail(String id, String day) {
        Map resMap = new HashMap();

        List<Map> dataMapList = new ArrayList<>();
        Date startDate = DateUtils.dateTime("yyyy-MM-dd HH:mm:ss",day+" 00:00:00");
        Date endDate = DateUtils.dateTime("yyyy-MM-dd HH:mm:ss",day+" 23:59:59");

        BusWaterAutomonitorevaluateDaydata daydataParam = new BusWaterAutomonitorevaluateDaydata();
        daydataParam.setSegmentid(id);
        daydataParam.setStartTime(startDate);
        daydataParam.setEndTime(endDate);
        List<BusWaterAutomonitorevaluateDaydata> daydataList = busWaterAutomonitorevaluateDaydataMapper.selectBusWaterAutomonitorevaluateDaydataList(daydataParam);
        if(!CollectionUtils.isEmpty(daydataList)){
            BusWaterAutomonitorevaluateDaydata daydata = daydataList.get(0);
            resMap.put("qualitylevelname",daydata.getQualitylevelname());
            resMap.put("segmentindex",daydata.getSegmentindex());
        }else{
            resMap.put("qualitylevelname","");
            resMap.put("segmentindex","");
        }

        BusWaterAutomonitorDaydata param = new BusWaterAutomonitorDaydata();
        param.setSegmentid(id);
        param.setStartTime(startDate);
        param.setEndTime(endDate);
        List<BusWaterAutomonitorDaydata> dataList = selectBusWaterAutomonitorDaydataList(param);

        BussinessItemVo vo = new BussinessItemVo();
        vo.setBussinessCategoryCode("Auto");
        List<Map<String,Object>> itemList=publicToolsService.bussinessItemData(vo);
        for (Map<String, Object> itemMap : itemList) {
            String itemName = StringUtils.getString(itemMap.get("itemName"));
            String effectiveValue = "";
            String qualityLevelName = "";
            if(!CollectionUtils.isEmpty(dataList)){
                for (BusWaterAutomonitorDaydata busWaterAutomonitorDaydata : dataList) {
                    if(itemName.equals(busWaterAutomonitorDaydata.getItemname())){
                        if(busWaterAutomonitorDaydata.getEffectivevalue() != null){
                            effectiveValue = String.valueOf(busWaterAutomonitorDaydata.getEffectivevalue());
                        }
                        qualityLevelName = busWaterAutomonitorDaydata.getQualitylevelname();
                        break;
                    }
                }
            }
            Map dataMap = new HashMap();
            dataMap.put("itemName",itemName);
            dataMap.put("effectiveValue",effectiveValue);
            dataMap.put("qualityLevelName",qualityLevelName);
            dataMapList.add(dataMap);
        }
        resMap.put("dataList",dataMapList);

        return resMap;
    }

    @Override
    public Map weeklyReport(String id, Date startTime,Date endTime) {
        Map resMap = new LinkedHashMap();
        BusWaterSegment busWaterSegment = busWaterSegmentMapper.selectBusWaterSegmentByID(id);
        List<List<String>> dataList = new ArrayList<>();

        Set<String> cbItems = new HashSet<>();

        Integer targetLevel = 0;
        if(StringUtils.isNotEmpty(busWaterSegment.getTargetlevel())){
            targetLevel = Integer.parseInt(busWaterSegment.getTargetlevel());
        }

        int columnCounts = 1;
        List<Map> tableOp = new ArrayList<>();
        //检测因子
        BussinessItemVo vo = new BussinessItemVo();
        vo.setBussinessCategoryCode("Auto");
        List<Map<String,Object>> itemList=publicToolsService.bussinessItemData(vo);

        //监测因子标准值
        Map<String,List<Standard>> itemStandardsMap = new LinkedHashMap<>();
        Map<String,String> itemNameToCodeMap = new HashMap<>();
        //先生成表头
        List<String> titleList1 = new ArrayList<>();
        titleList1.add("时间");
        List<String> titleList2 = new ArrayList<>();
        titleList2.add("时间");

        int columnCount = 1;
        Map tableOpMap1 = new LinkedHashMap();
        tableOpMap1.put("prop","column"+columnCount);
        tableOpMap1.put("label","时间");
        tableOp.add(tableOpMap1);

        Map isevaluteMap = new HashMap<>();
        Map<String,Integer> keepPointBitsMap = new HashMap<>();
        for (Map<String, Object> stringObjectMap : itemList) {
            columnCount ++;
            String itemName = StringUtils.getString(stringObjectMap.get("itemName"));
            String unit = StringUtils.getString(stringObjectMap.get("unit"));
            if(StringUtils.isEmpty(unit)){
                unit = "无量纲";
            }
            isevaluteMap.put(itemName,stringObjectMap.get("isEvalute"));
            Map tableOpMap = new LinkedHashMap();
            tableOpMap.put("prop","column"+columnCount);
            tableOpMap.put("label",itemName+"("+unit+")");
            tableOp.add(tableOpMap);

            titleList1.add(StringUtils.getString(stringObjectMap.get("itemName")));
            titleList2.add(StringUtils.getString(stringObjectMap.get("unit")));
            columnCounts++;

            Map segmentStandardValuemap = new HashMap();
            segmentStandardValuemap.put("ItemCode", StringUtils.getString(stringObjectMap.get("itemCode")));
            segmentStandardValuemap.put("ID", id);
            List<Standard> standards = segmentFormula.segmentStandardValue(segmentStandardValuemap);
            itemStandardsMap.put(StringUtils.getString(stringObjectMap.get("itemName")),standards);

            itemNameToCodeMap.put(StringUtils.getString(stringObjectMap.get("itemName")),StringUtils.getString(stringObjectMap.get("itemCode")));
            Integer keepPointBits = 1;
            if(StringUtils.isNotEmpty(StringUtils.getString(stringObjectMap.get("keepPointBits")))){
                keepPointBits = Integer.parseInt(StringUtils.getString(stringObjectMap.get("keepPointBits")));
            }
            keepPointBitsMap.put(itemName,keepPointBits);
        }
        dataList.add(titleList1);
        dataList.add(titleList2);


        List<Map> tableData = new ArrayList<>();

        BusWaterAutomonitorDaydata daydataParam = new BusWaterAutomonitorDaydata();
        daydataParam.setSegmentid(id);
        daydataParam.setStartTime(startTime);
        daydataParam.setEndTime(endTime);
        List<BusWaterAutomonitorDaydata> daydataList = selectBusWaterAutomonitorDaydataList(daydataParam);
        if(!CollectionUtils.isEmpty(daydataList)){
            daydataList.sort(Comparator.comparing(BusWaterAutomonitorDaydata::getSampletime));
            List<String> timeList = new ArrayList<>();
            for (BusWaterAutomonitorDaydata daydata : daydataList) {
                String dataTime = DateUtils.parseDateToStr("yyyy-MM-dd",daydata.getSampletime());
                if(!timeList.contains(dataTime)){
                    timeList.add(dataTime);
                }
            }

            Map<String,Float> maxDataMap = new LinkedHashMap<>();
            Map<String,Float> minDataMap = new LinkedHashMap<>();
            Map<String,Float> totalValueMap = new LinkedHashMap<>();
            Map<String,Float> countMap = new LinkedHashMap<>();

            for (String time : timeList) {
                int column = 1;
                List<String> list = new ArrayList<>();
                list.add(time);

                Map tableDataMap = new LinkedHashMap();
                tableDataMap.put("column"+column,time);
                tableDataMap.put("column"+column+"_v","0");
                for (Map<String, Object> stringObjectMap : itemList) {
                    column++;
                    String value = "";
                    String isoverstandard = "";
                    Integer keepPointBits = 1;
                    if(StringUtils.isNotEmpty(StringUtils.getString(stringObjectMap.get("keepPointBits")))){
                        keepPointBits = Integer.parseInt(StringUtils.getString(stringObjectMap.get("keepPointBits")));
                    }
                    if(!maxDataMap.containsKey(StringUtils.getString(stringObjectMap.get("itemName")))){
                        maxDataMap.put(StringUtils.getString(stringObjectMap.get("itemName")),Float.MIN_VALUE);
                    }
                    if(!minDataMap.containsKey(StringUtils.getString(stringObjectMap.get("itemName")))){
                        minDataMap.put(StringUtils.getString(stringObjectMap.get("itemName")),Float.MAX_VALUE);
                    }
                    if(!totalValueMap.containsKey(StringUtils.getString(stringObjectMap.get("itemName")))){
                        totalValueMap.put(StringUtils.getString(stringObjectMap.get("itemName")),0f);
                    }
                    if(!countMap.containsKey(StringUtils.getString(stringObjectMap.get("itemName")))){
                        countMap.put(StringUtils.getString(stringObjectMap.get("itemName")),0f);
                    }


                    for (BusWaterAutomonitorDaydata hourdata : daydataList) {
                        String dataTime = DateUtils.parseDateToStr("yyyy-MM-dd",hourdata.getSampletime());
                        String itemName = hourdata.getItemname();

                        if(time.equals(dataTime) && itemName.equals(StringUtils.getString(stringObjectMap.get("itemName")))){
                            if(hourdata.getEffectivevalue() != null){
                                if(maxDataMap.containsKey(itemName)){
                                    float oldValue = maxDataMap.get(itemName);
                                    if(oldValue<hourdata.getEffectivevalue().floatValue()){
                                        maxDataMap.put(itemName,hourdata.getEffectivevalue().floatValue());
                                    }
                                }else{
                                    maxDataMap.put(itemName,hourdata.getEffectivevalue().floatValue());
                                }

                                if(minDataMap.containsKey(itemName)){
                                    float oldValue = minDataMap.get(itemName);
                                    if(oldValue>hourdata.getEffectivevalue().floatValue()){
                                        minDataMap.put(itemName,hourdata.getEffectivevalue().floatValue());
                                    }
                                }else{
                                    minDataMap.put(itemName,hourdata.getEffectivevalue().floatValue());
                                }

                                if(totalValueMap.containsKey(itemName)){
                                    float oldValue = totalValueMap.get(itemName);
                                    totalValueMap.put(itemName,oldValue+hourdata.getEffectivevalue().floatValue());
                                }else{
                                    totalValueMap.put(itemName,hourdata.getEffectivevalue().floatValue());
                                }

                                if(countMap.containsKey(itemName)){
                                    float oldValue = countMap.get(itemName);
                                    countMap.put(itemName,oldValue+1);
                                }else{
                                    countMap.put(itemName,1f);
                                }
                            }
                            value = String.format("%."+keepPointBits+"f",hourdata.getEffectivevalue().floatValue());
                            isoverstandard = hourdata.getIsoverstandard();
                            break;


                        }
                    }
                    tableDataMap.put("column"+column,value);
                    tableDataMap.put("column"+column+"_v",isoverstandard);
                    list.add(value+";"+isoverstandard);
                }
                dataList.add(list);
                tableData.add(tableDataMap);
            }

            //最大值
            if(!maxDataMap.isEmpty()){
                List<String> list = new ArrayList<>();
                list.add("最大值");
                int column = 1;
                Map tableDataMap = new LinkedHashMap();
                tableDataMap.put("column"+column,"最大值");
                tableDataMap.put("column"+column+"_v","0");

                for (String key : maxDataMap.keySet()) {
                    Integer keepPointBits = keepPointBitsMap.get(key);
                    column ++;
                    if(maxDataMap.get(key) == Float.MIN_VALUE){
                        list.add("");
                        tableDataMap.put("column"+column,"");
                        tableDataMap.put("column"+column+"_v","0");
                    }else{
                        String value = String.format("%."+keepPointBits+"f",maxDataMap.get(key));
                        list.add(value);
                        tableDataMap.put("column"+column,value);
                        tableDataMap.put("column"+column+"_v","0");
                    }
                }
                tableData.add(tableDataMap);
                dataList.add(list);
            }
            //最小值
            if(!minDataMap.isEmpty()){
                List<String> list = new ArrayList<>();
                list.add("最小值");
                int column = 1;
                Map tableDataMap = new LinkedHashMap();
                tableDataMap.put("column"+column,"最小值");
                tableDataMap.put("column"+column+"_v","0");
                for (String key : minDataMap.keySet()) {
                    column++;
                    Integer keepPointBits = keepPointBitsMap.get(key);
                    if(minDataMap.get(key) == Float.MAX_VALUE){
                        list.add("");
                        tableDataMap.put("column"+column,"");
                        tableDataMap.put("column"+column+"_v","0");
                    }else{
                        String value = String.format("%."+keepPointBits+"f",minDataMap.get(key));
                        list.add(value);
                        tableDataMap.put("column"+column,value);
                        tableDataMap.put("column"+column+"_v","0");
                    }
                }
                tableData.add(tableDataMap);
                dataList.add(list);
            }

            //均值
            Integer maxValue = Integer.MIN_VALUE;
            if(!countMap.isEmpty()){
                List<String> list = new ArrayList<>();
                list.add("均值");
                List<String> szList = new ArrayList<>();
                szList.add("各项水质");
                int column = 1;
                Map tableDataMap = new LinkedHashMap();
                tableDataMap.put("column"+column,"均值");

                Map szTableDataMap = new LinkedHashMap();
                szTableDataMap.put("column"+column,"各项水质");

                for (String key : countMap.keySet()) {
                    column++;
                    Integer keepPointBits = keepPointBitsMap.get(key);
                    if(countMap.get(key)>0){
                        Float value = totalValueMap.get(key)/countMap.get(key);
                        list.add(String.format("%."+keepPointBits+"f",value));
                        tableDataMap.put("column"+column,String.format("%."+keepPointBits+"f",value));
                        tableDataMap.put("column"+column+"_v","0");
                        Integer integer = ItemCodeOverData.GetSingleType(Double.valueOf(String.valueOf(value)), itemStandardsMap.get(key), String.valueOf(itemNameToCodeMap.get(key)), String.valueOf(value), Integer.valueOf(busWaterSegment.getSegmentcategory()));
                        if(integer == null){
                            integer = 0;
                        }
                        if(integer>maxValue && "1".equals(StringUtils.getString(isevaluteMap.get(key)))){
                            maxValue = integer.intValue();
                        }
                        String levelName = WaterLevelCompute.GetLevelName(integer,"无类别");
                        szList.add(levelName);
                        szTableDataMap.put("column"+column,levelName);
                        szTableDataMap.put("column"+column+"_v","0");
                        if(integer>targetLevel){
                            szTableDataMap.put("column"+column+"_v","1");
                            if("1".equals(StringUtils.getString(isevaluteMap.get(key)))){
                                cbItems.add(key);
                            }
                        }else{
                            szTableDataMap.put("column"+column+"_v","0");
                        }
                    }else{
                        list.add("");
                        szList.add("");
                        tableDataMap.put("column"+column,"");
                        tableDataMap.put("column"+column+"_v","0");
                        szTableDataMap.put("column"+column,"");
                        szTableDataMap.put("column"+column+"_v","0");
                    }
                }
                tableData.add(tableDataMap);
                tableData.add(szTableDataMap);


                List<String> ztszList = new ArrayList<>();
                ztszList.add("整体水质");
                String levelName = WaterLevelCompute.GetLevelName(maxValue,"无类别");

                int ztszcolumn = 1;
                Map ztsctableDataMap = new LinkedHashMap();
                ztsctableDataMap.put("column"+ztszcolumn,"整体水质");
                ztsctableDataMap.put("column"+column+"_v","0");
                for (String key : countMap.keySet()) {
                    ztszcolumn++;
                    ztsctableDataMap.put("column"+ztszcolumn,levelName);
                    ztsctableDataMap.put("column"+column+"_v","0");
                    ztszList.add(levelName);
                }
                tableData.add(ztsctableDataMap);
                dataList.add(list);
                dataList.add(szList);
                dataList.add(ztszList);
            }
            //超标项
            List<String> cbList = new ArrayList<>();
            cbList.add("超标项");
            int column = 1;
            Map tableDataMap = new LinkedHashMap();
            tableDataMap.put("column"+column,"超标项");
            tableDataMap.put("column"+column+"_v","0");

            String cbItemStr = "";
            for (String cbItem : cbItems) {
                if(StringUtils.isEmpty(cbItemStr)){
                    cbItemStr = cbItem;
                }else {
                    cbItemStr = cbItemStr + ","+cbItem;
                }
            }
            for(int i=0;i<columnCounts;i++){
                column++;
                tableDataMap.put("column"+column,cbItemStr);
                tableDataMap.put("column"+column+"_v","0");
                cbList.add(cbItemStr);
            }
            tableData.add(tableDataMap);
            dataList.add(cbList);
        }
        resMap.put("tableOp",tableOp);
        resMap.put("tableData",tableData);
        return resMap;
    }

    @Override
    public Map autoQualityCalendar(String year, String segmentId,String itemCode, String isOverStandard) {
        Map resMap = new HashMap();

        Date startDate = DateUtils.dateTime("yyyy-MM-dd HH:mm:ss",year+"-01-01 00:00:00");
        Date endDate = DateUtils.dateTime("yyyy-MM-dd HH:mm:ss",year+"-12-31 23:59:59");
        BusWaterAutomonitorDaydata param = new BusWaterAutomonitorDaydata();
        param.setStartTime(startDate);
        param.setEndTime(endDate);
        param.setSegmentid(segmentId);
        param.setItemcode(itemCode);
        if(StringUtils.isNotEmpty(isOverStandard)){
            param.setIsoverstandard(isOverStandard);
        }
        int excellentThreeDays = 0;
        String excellentThreeProportion = "0%";
        int standardDays = 0;
        String standardProportion  = "0%";
        int allDays = 0;

        List<BusWaterAutomonitorDaydata> daydataList = selectBusWaterAutomonitorDaydataList(param);
        if(!CollectionUtils.isEmpty(daydataList)){
            allDays = daydataList.size();
            for (BusWaterAutomonitorDaydata daydata : daydataList) {
                if("1".equals(daydata.getQualitylevel()) ||"2".equals(daydata.getQualitylevel()) || "3".equals(daydata.getQualitylevel())){
                    excellentThreeDays++;
                }
                if("0".equals(daydata.getIsoverstandard())){
                    standardDays++;
                }
            }
        }
        if(allDays>0){
            excellentThreeProportion = String.format("%.1f",((float)excellentThreeDays/(float)allDays)*100f)+"%";
            standardProportion  = String.format("%.1f",((float)standardDays/(float)allDays)*100f)+"%";
        }

        resMap.put("excellentDays",excellentThreeDays);
        resMap.put("excellentProportion",excellentThreeProportion);
        resMap.put("standardDays",standardDays);
        resMap.put("standardProportion",standardProportion);

        Map<String,List<Map>> monthMap = new LinkedHashMap();
        while(startDate.before(endDate)){
            String month = DateUtils.parseDateToStr("yyyy-MM",startDate);
            String day = DateUtils.parseDateToStr("yyyy-MM-dd",startDate);
            String qualityLevelName = "";
            String qualityLevel = "";
            String overStandard = "";
            if(!CollectionUtils.isEmpty(daydataList)){
                for (BusWaterAutomonitorDaydata daydata : daydataList) {
                    String dataDay = DateUtils.parseDateToStr("yyyy-MM-dd",daydata.getSampletime());
                    if(dataDay.equals(day)){
                        qualityLevelName = daydata.getQualitylevelname();
                        qualityLevel = daydata.getQualitylevel();
                        overStandard = daydata.getIsoverstandard();
                        break;
                    }
                }
            }
            Map dataMap = new HashMap();
            dataMap.put("day",day);
            dataMap.put("qualityLevelName",qualityLevelName);
            dataMap.put("qualityLevel",qualityLevel);
            if("0".equals(overStandard)){
                dataMap.put("standard","1");
            }else{
                dataMap.put("standard","0");
            }
            if(monthMap.containsKey(month)){
                List<Map> dataList = monthMap.get(month);
                dataList.add(dataMap);
                monthMap.put(month,dataList);
            }else{
                List<Map> dataList = new ArrayList<>();
                dataList.add(dataMap);
                monthMap.put(month,dataList);
            }
            startDate = DateUtils.addDays(startDate,1);
        }

        List<Map> monthDataList = new ArrayList<>();

        Set<String> keySet = monthMap.keySet();
        for (String key : keySet) {
            Map monthData = new HashMap();
            monthData.put("month",key);
            int standardCount = 0;
            List<Map> mapList = monthMap.get(key);
            for (Map map : mapList) {
                if("1".equals(map.get("standard"))){
                    standardCount++;
                }
            }
            monthData.put("standardDays",standardCount);
            monthData.put("standardProportion",String.format("%.1f",((float)standardCount/(float)mapList.size())*100f)+"%");
            monthData.put("dayDataList",mapList);
            monthDataList.add(monthData);
        }
        resMap.put("monthDataList",monthDataList);
        return resMap;
    }

    @Override
    public List<Map<String, Object>> getWaterAutoMonitorDayList(Map<String, Object> params) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        if (StringUtils.isEmpty(params.get("beginTime")!=null  ? params.get("beginTime").toString() : "") || StringUtils.isEmpty(params.get("endTime")!=null ? params.get("endTime").toString() : "")){
            params.put("beginTime", DateUtils.getFirstDayOfMonth(DateUtils.addMonths(DateUtils.getNowDate(),-1)));
            params.put("endTime", DateUtils.getLastDayOfMonth(DateUtils.addMonths(DateUtils.getNowDate(),-1)));
        }else {
            params.put("beginTime", DateUtils.getFirstDayOfMonth(DateUtils.parseDate(params.get("beginTime").toString())));
            params.put("endTime", DateUtils.getLastDayOfMonth(DateUtils.parseDate(params.get("endTime").toString())));
        }
        List<Map<String, Object>> dataList= busWaterAutomonitorDaydataMapper.getWaterAutoMonitorDayList(params);
        if(StringUtils.isNotEmpty(dataList)){
            //获取检测因子配置
            BussinessItemVo vo = new BussinessItemVo();
            vo.setBussinessCategoryCode("Auto");
            List<Map<String, Object>> itemList = publicToolsService.bussinessItemData(vo);
            // 对dataList 进行分组，按segmentId进行分组
            Map<String,List<Map<String, Object>>> segmentIdMap = dataList.stream().collect(
                    Collectors.groupingBy(map -> (String)map.get("segmentId"))
            );
            // 循环分组的数据
            segmentIdMap.forEach((segmentId, segmentIdList) -> {
                // 对segmentIdList 按时间分组sampleTime
                Map<String,List<Map<String, Object>>> segmentTimeMap = segmentIdList.stream().collect(
                        Collectors.groupingBy(map -> (String)map.get("sampleTime"))
                );
                // 循环分组的数据进行行转列
                segmentTimeMap.forEach((sampleTime, dataTimeList) -> {
                    Map<String,Object> dataMap = new HashMap();
                    dataMap.put("segmentId",dataTimeList.get(0).get("segmentId"));
                    dataMap.put("segmentName",dataTimeList.get(0).get("segmentName"));
                    dataMap.put("sampleTime",sampleTime);
                    dataTimeList.forEach(map -> {
                        itemList.forEach(itemMap -> {
                            String itemCode = StringUtils.getString(map.get("itemCode"));
                            if(itemCode.equals(itemMap.get("itemCode"))){
                                dataMap.put(itemMap.get("eNName").toString(),map.get("effectiveValue"));
                            }
                        });
                    });
                    resultList.add(dataMap);
                });
            });
        }
        return resultList;
    }

    @Override
    public Map yearReport(String id, Date startTime,Date endTime) {
        Map resMap = new LinkedHashMap();

        BusWaterSegment busWaterSegment = busWaterSegmentMapper.selectBusWaterSegmentByID(id);
        List<List<String>> dataList = new ArrayList<>();

        Set<String> cbItems = new HashSet<>();

        Integer targetLevel = 0;
        if(StringUtils.isNotEmpty(busWaterSegment.getTargetlevel())){
            targetLevel = Integer.parseInt(busWaterSegment.getTargetlevel());
        }

        List<Map> tableOp = new ArrayList<>();
        int columnCounts = 1;

        //检测因子
        BussinessItemVo vo = new BussinessItemVo();
        vo.setBussinessCategoryCode("Auto");
        List<Map<String,Object>> itemList=publicToolsService.bussinessItemData(vo);

        //监测因子标准值
        Map<String,List<Standard>> itemStandardsMap = new LinkedHashMap<>();
        Map<String,String> itemNameToCodeMap = new HashMap<>();
        //先生成表头
        List<String> titleList1 = new ArrayList<>();
        titleList1.add("时间");
        List<String> titleList2 = new ArrayList<>();
        titleList2.add("时间");

        int columnCount = 1;
        Map tableOpMap1 = new LinkedHashMap();
        tableOpMap1.put("prop","column"+columnCount);
        tableOpMap1.put("label","时间");
        tableOp.add(tableOpMap1);
        Map isevaluteMap = new HashMap<>();
        Map<String,Integer> keepPointBitsMap = new HashMap<>();
        for (Map<String, Object> stringObjectMap : itemList) {
            columnCount ++;
            String itemName = StringUtils.getString(stringObjectMap.get("itemName"));
            String unit = StringUtils.getString(stringObjectMap.get("unit"));
            if(StringUtils.isEmpty(unit)){
                unit = "无量纲";
            }
            isevaluteMap.put(itemName,stringObjectMap.get("isEvalute"));
            Map tableOpMap = new LinkedHashMap();
            tableOpMap.put("prop","column"+columnCount);
            tableOpMap.put("label",itemName+"("+unit+")");
            tableOp.add(tableOpMap);

            titleList1.add(StringUtils.getString(stringObjectMap.get("itemName")));
            titleList2.add(StringUtils.getString(stringObjectMap.get("unit")));
            columnCounts++;

            Map segmentStandardValuemap = new HashMap();
            segmentStandardValuemap.put("ItemCode", StringUtils.getString(stringObjectMap.get("itemCode")));
            segmentStandardValuemap.put("ID", id);
            List<Standard> standards = segmentFormula.segmentStandardValue(segmentStandardValuemap);
            itemStandardsMap.put(StringUtils.getString(stringObjectMap.get("itemName")),standards);

            itemNameToCodeMap.put(StringUtils.getString(stringObjectMap.get("itemName")),StringUtils.getString(stringObjectMap.get("itemCode")));
            Integer keepPointBits = 1;
            if(StringUtils.isNotEmpty(StringUtils.getString(stringObjectMap.get("keepPointBits")))){
                keepPointBits = Integer.parseInt(StringUtils.getString(stringObjectMap.get("keepPointBits")));
            }
            keepPointBitsMap.put(itemName,keepPointBits);
        }
        dataList.add(titleList1);
        dataList.add(titleList2);

        List<Map> tableData = new ArrayList<>();

        BusWaterAutomonitorDaydata daydataParam = new BusWaterAutomonitorDaydata();
        daydataParam.setSegmentid(id);
        daydataParam.setStartTime(startTime);
        daydataParam.setEndTime(endTime);
        List<BusWaterAutomonitorDaydata> daydataList = selectBusWaterAutomonitorDaydataList(daydataParam);
        if(!CollectionUtils.isEmpty(daydataList)){
            daydataList.sort(Comparator.comparing(BusWaterAutomonitorDaydata::getSampletime));
            List<String> timeList = new ArrayList<>();
            for (BusWaterAutomonitorDaydata daydata : daydataList) {
                String dataTime = DateUtils.parseDateToStr("yyyy-MM",daydata.getSampletime());
                if(!timeList.contains(dataTime)){
                    timeList.add(dataTime);
                }
            }

            Map<String,Float> maxDataMap = new LinkedHashMap<>();
            Map<String,Float> minDataMap = new LinkedHashMap<>();
            Map<String,Float> totalValueMap = new LinkedHashMap<>();
            Map<String,Float> countMap = new LinkedHashMap<>();

            for (String time : timeList) {
                List<String> list = new ArrayList<>();
                list.add(time);
                int column = 1;
                Map tableDataMap = new LinkedHashMap();
                tableDataMap.put("column"+column,time);
                tableDataMap.put("column"+column+"_v","0");
                for (Map<String, Object> stringObjectMap : itemList) {
                    column++;
                    String value = "";
                    String isoverstandard = "";
                    Integer keepPointBits = 1;
                    if(StringUtils.isNotEmpty(StringUtils.getString(stringObjectMap.get("keepPointBits")))){
                        keepPointBits = Integer.parseInt(StringUtils.getString(stringObjectMap.get("keepPointBits")));
                    }

                    if(!maxDataMap.containsKey(StringUtils.getString(stringObjectMap.get("itemName")))){
                        maxDataMap.put(StringUtils.getString(stringObjectMap.get("itemName")),Float.MIN_VALUE);
                    }
                    if(!minDataMap.containsKey(StringUtils.getString(stringObjectMap.get("itemName")))){
                        minDataMap.put(StringUtils.getString(stringObjectMap.get("itemName")),Float.MAX_VALUE);
                    }
                    if(!totalValueMap.containsKey(StringUtils.getString(stringObjectMap.get("itemName")))){
                        totalValueMap.put(StringUtils.getString(stringObjectMap.get("itemName")),0f);
                    }
                    if(!countMap.containsKey(StringUtils.getString(stringObjectMap.get("itemName")))){
                        countMap.put(StringUtils.getString(stringObjectMap.get("itemName")),0f);
                    }


                    for (BusWaterAutomonitorDaydata hourdata : daydataList) {
                        String dataTime = DateUtils.parseDateToStr("yyyy-MM",hourdata.getSampletime());
                        String itemName = hourdata.getItemname();

                        if(time.equals(dataTime) && itemName.equals(StringUtils.getString(stringObjectMap.get("itemName")))){
                            if(hourdata.getEffectivevalue() != null){
                                if(maxDataMap.containsKey(itemName)){
                                    float oldValue = maxDataMap.get(itemName);
                                    if(oldValue<hourdata.getEffectivevalue().floatValue()){
                                        maxDataMap.put(itemName,hourdata.getEffectivevalue().floatValue());
                                    }
                                }else{
                                    maxDataMap.put(itemName,hourdata.getEffectivevalue().floatValue());
                                }

                                if(minDataMap.containsKey(itemName)){
                                    float oldValue = minDataMap.get(itemName);
                                    if(oldValue>hourdata.getEffectivevalue().floatValue()){
                                        minDataMap.put(itemName,hourdata.getEffectivevalue().floatValue());
                                    }
                                }else{
                                    minDataMap.put(itemName,hourdata.getEffectivevalue().floatValue());
                                }

                                if(totalValueMap.containsKey(itemName)){
                                    float oldValue = totalValueMap.get(itemName);
                                    totalValueMap.put(itemName,oldValue+hourdata.getEffectivevalue().floatValue());
                                }else{
                                    totalValueMap.put(itemName,hourdata.getEffectivevalue().floatValue());
                                }

                                if(countMap.containsKey(itemName)){
                                    float oldValue = countMap.get(itemName);
                                    countMap.put(itemName,oldValue+1);
                                }else{
                                    countMap.put(itemName,1f);
                                }
                            }
                            value = String.format("%."+keepPointBits+"f",hourdata.getEffectivevalue().floatValue());
                            isoverstandard = hourdata.getIsoverstandard();
                            break;


                        }
                    }
                    list.add(value+";"+isoverstandard);
                    tableDataMap.put("column"+column,value);
                    tableDataMap.put("column"+column+"_v",isoverstandard);
                }
                tableData.add(tableDataMap);
                dataList.add(list);
            }

            //最大值
            if(!maxDataMap.isEmpty()){
                List<String> list = new ArrayList<>();
                list.add("最大值");
                int column = 1;
                Map tableDataMap = new LinkedHashMap();
                tableDataMap.put("column"+column,"最大值");
                tableDataMap.put("column"+column+"_v","0");
                for (String key : maxDataMap.keySet()) {
                    column ++;
                    Integer keepPointBits = keepPointBitsMap.get(key);
                    if(maxDataMap.get(key) == Float.MIN_VALUE){
                        list.add("");
                        tableDataMap.put("column"+column,"");
                        tableDataMap.put("column"+column+"_v","0");
                    }else{
                        String value = String.format("%."+keepPointBits+"f",maxDataMap.get(key));
                        list.add(value);
                        tableDataMap.put("column"+column,value);
                        tableDataMap.put("column"+column+"_v","0");
                    }
                }
                tableData.add(tableDataMap);
                dataList.add(list);
            }
            //最小值
            if(!minDataMap.isEmpty()){
                List<String> list = new ArrayList<>();
                list.add("最小值");
                int column = 1;
                Map tableDataMap = new LinkedHashMap();
                tableDataMap.put("column"+column,"最小值");
                tableDataMap.put("column"+column+"_v","0");
                for (String key : minDataMap.keySet()) {
                    column ++;
                    Integer keepPointBits = keepPointBitsMap.get(key);
                    if(minDataMap.get(key) == Float.MAX_VALUE){
                        list.add("");
                        tableDataMap.put("column"+column,"");
                        tableDataMap.put("column"+column+"_v","0");
                    }else{
                        String value = String.format("%."+keepPointBits+"f",minDataMap.get(key));
                        list.add(value);
                        tableDataMap.put("column"+column,value);
                        tableDataMap.put("column"+column+"_v","0");
                    }
                }
                tableData.add(tableDataMap);
                dataList.add(list);
            }

            //均值
            Integer maxValue = Integer.MIN_VALUE;
            if(!countMap.isEmpty()){
                List<String> list = new ArrayList<>();
                list.add("均值");
                List<String> szList = new ArrayList<>();
                szList.add("各项水质");

                int column = 1;
                Map tableDataMap = new LinkedHashMap();
                tableDataMap.put("column"+column,"均值");

                Map szTableDataMap = new LinkedHashMap();
                szTableDataMap.put("column"+column,"各项水质");

                for (String key : countMap.keySet()) {
                    column++;
                    Integer keepPointBits = keepPointBitsMap.get(key);
                    if(countMap.get(key)>0){
                        Float value = totalValueMap.get(key)/countMap.get(key);
                        list.add(String.format("%."+keepPointBits+"f",value));
                        tableDataMap.put("column"+column,String.format("%."+keepPointBits+"f",value));
                        tableDataMap.put("column"+column+"_v","0");

                        Integer integer = ItemCodeOverData.GetSingleType(Double.valueOf(String.valueOf(value)), itemStandardsMap.get(key), String.valueOf(itemNameToCodeMap.get(key)), String.valueOf(value), Integer.valueOf(busWaterSegment.getSegmentcategory()));
                        if(integer == null){
                            integer = 0;
                        }
                        if(integer>maxValue && "1".equals(StringUtils.getString(isevaluteMap.get(key)))){
                            maxValue = integer.intValue();
                        }
                        String levelName = WaterLevelCompute.GetLevelName(integer,"无类别");
                        szList.add(levelName);
                        szTableDataMap.put("column"+column,levelName);
                        szTableDataMap.put("column"+column+"_v","0");
                        if(integer>targetLevel){
                            szTableDataMap.put("column"+column+"_v","1");
                            if("1".equals(StringUtils.getString(isevaluteMap.get(key)))){
                                cbItems.add(key);
                            }
                        }else{
                            szTableDataMap.put("column"+column+"_v","0");
                        }
                    }else{
                        list.add("");
                        szList.add("");
                        tableDataMap.put("column"+column,"");
                        tableDataMap.put("column"+column+"_v","0");
                        szTableDataMap.put("column"+column,"");
                        szTableDataMap.put("column"+column+"_v","0");
                    }
                }
                tableData.add(tableDataMap);
                tableData.add(szTableDataMap);

                List<String> ztszList = new ArrayList<>();
                ztszList.add("整体水质");
                int ztszcolumn = 1;
                Map ztsctableDataMap = new LinkedHashMap();
                ztsctableDataMap.put("column"+ztszcolumn,"整体水质");
                ztsctableDataMap.put("column"+column+"_v","0");

                String levelName = WaterLevelCompute.GetLevelName(maxValue,"无类别");
                for (String key : countMap.keySet()) {
                    ztszList.add(levelName);
                    ztszcolumn++;
                    ztsctableDataMap.put("column"+ztszcolumn,levelName);
                    ztsctableDataMap.put("column"+column+"_v","0");
                }
                tableData.add(ztsctableDataMap);
                dataList.add(list);
                dataList.add(szList);
                dataList.add(ztszList);
            }
            //超标项
            List<String> cbList = new ArrayList<>();
            cbList.add("超标项");
            String cbItemStr = "";
            int column = 1;
            Map tableDataMap = new LinkedHashMap();
            tableDataMap.put("column"+column,"超标项");
            tableDataMap.put("column"+column+"_v","0");

            for (String cbItem : cbItems) {
                if(StringUtils.isEmpty(cbItemStr)){
                    cbItemStr = cbItem;
                }else {
                    cbItemStr = cbItemStr + ","+cbItem;
                }
            }
            for(int i=0;i<columnCounts;i++){
                column++;
                tableDataMap.put("column"+column,cbItemStr);
                tableDataMap.put("column"+column+"_v","0");
                cbList.add(cbItemStr);
            }
            tableData.add(tableDataMap);
            dataList.add(cbList);
        }
        resMap.put("tableOp",tableOp);
        resMap.put("tableData",tableData);
        return resMap;
    }
}
